﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CivilleWP7.Views.Controls;
using System.Collections.ObjectModel;
using CivilleWP7.Civille.Source;
using System.Data.Services.Client;
using CivilleWP7.CivilleDataServiceReference;
using Microsoft.Phone.Shell;
using SL.Phone.Federation.Utilities;
using System.Windows.Media.Imaging;

namespace CivilleWP7.Views.Pages
{
    public partial class TasksPivotPage : PhoneApplicationPage
    {
        private bool IsLightTheme;
        public TasksPivotPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(TasksPivotPage_Loaded);

            displayApplicationBar();
            setBackground();
        }
        void setBackground()
        {
            checkThemeColor();
            ImageBrush myBrush = new ImageBrush();
            if(IsLightTheme)
                myBrush.ImageSource=new BitmapImage(new Uri("/Resources/Images/Backgroundwhite.jpg",UriKind.Relative));
            else
                myBrush.ImageSource = new BitmapImage(new Uri("/Resources/Images/Background.jpg",UriKind.Relative));
            ContentPanel.Background=myBrush;
        }
        void checkThemeColor()
        {
            var visibility = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];
            if (visibility == Visibility.Visible)
                IsLightTheme = true;
            else
                IsLightTheme = false;
        }
        void displayApplicationBar()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = true;
            addSearchButton();
        }
        void addSearchButton()
        {
            checkThemeColor();
            ApplicationBarIconButton button1;
            if (IsLightTheme)
                button1 = new ApplicationBarIconButton(new Uri("/Resources/Icons/Light/appbar.feature.search.rest.png", UriKind.Relative));
            else
                button1 = new ApplicationBarIconButton(new Uri("/Resources/Icons/Dark/appbar.feature.search.rest.png", UriKind.Relative));
            button1.Text = "Search task";
            button1.Click += new EventHandler(button1_Click);
            ApplicationBar.Buttons.Add(button1);
        }

        void button1_Click(object sender, EventArgs e)
        {           
            NavigationService.Navigate(new Uri("/Views/Pages/SearchTaskResults.xaml?type=" + PivotControl.SelectedIndex + "&search=", UriKind.Relative));
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            DiamondListBox.Items.Clear();
            CarbonListBox.Items.Clear();
            AllListBox.Items.Clear();

            int selectedItemId = 0;
            try
            {
                selectedItemId = Int32.Parse(NavigationContext.QueryString["PivotItemId"]);
                if (this.PivotControl.Items.Count <= selectedItemId)
                {
                    selectedItemId = 0;
                }
            }
            catch (Exception ex)
            {
                selectedItemId = 0;
            }
            this.PivotControl.SelectedItem = this.PivotControl.Items.ElementAt(selectedItemId);
        }

        void TasksPivotPage_Loaded(object sender, RoutedEventArgs e)
        {
            CivilleDataServiceConnector.AllTasksQuery.BeginExecute(OnTasksQueryComplete, CivilleDataServiceConnector.AllTasksQuery);
        }

        private void OnTasksQueryComplete(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                this.CarbonListBox.Items.Clear();
                this.AllListBox.Items.Clear();
                this.DiamondListBox.Items.Clear();
                DataServiceQuery<Task> query = result.AsyncState as DataServiceQuery<Task>;
                Queue<Task> tasks = new Queue<Task>();
                foreach (Task task in query.EndExecute(result))
                {
                    CustomListItem taskControl = new CustomListItem();
                    taskControl.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(Task_Tap);
                    taskControl.Height = 75;
                    taskControl.ID = task.ID;                    
                    taskControl.TitleTxt.Text = task.Title.ToString();                    
                    taskControl.DescriptionTxt.Text = task.Description.ToString();                    
                    taskControl.Width = this.PivotControl.ActualWidth;
                    taskControl.Tag = task;

                    CustomListItem taskControl2 = new CustomListItem();
                    taskControl2.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(Task_Tap);
                    taskControl2.Height = 75;
                    taskControl2.ID = task.ID;
                    taskControl2.TitleTxt.Text = task.Title.ToString();
                    taskControl2.DescriptionTxt.Text = task.Description.ToString();
                    taskControl2.Width = this.PivotControl.ActualWidth;
                    taskControl2.Tag = task;

                    if (task.TaskTypeID == 1)
                    {
                        this.CarbonListBox.Items.Add(taskControl);
                    }
                    else
                    {
                        this.DiamondListBox.Items.Add(taskControl);
                    }
                    this.AllListBox.Items.Add(taskControl2);
                }
            });
        }

        void Task_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Task task = (Task)(sender as CustomListItem).Tag;
            TaskDetail.Task = task;
            NavigationService.Navigate(new Uri("/Views/Pages/TaskDetail.xaml", UriKind.Relative));
        }
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to log out?", "Log out", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                RequestSecurityTokenResponseStore _rstrStore = App.Current.Resources["rstrStore"] as RequestSecurityTokenResponseStore;
                _rstrStore.RequestSecurityTokenResponse = null;
                NavigationService.Navigate(new Uri("/Views/Pages/SelectAuthPage.xaml", UriKind.Relative));
            }
        }
    }
}
